﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;

namespace Poet
{
    /// <summary>
    /// View Model Base
    /// </summary>
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        /// <summary>
        /// Property values
        /// </summary>
        private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
        
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Gets the specified expression.
        /// </summary>
        /// <typeparam name="T">Property type</typeparam>
        /// <param name="expression">The expression.</param>
        /// <returns>Property value</returns>
        public T Get<T>(Expression<Func<T>> expression)
        {
            var propertyName = PropertyNameProvider.GetPropertyName(expression);

            object value;
            if (_values.TryGetValue(propertyName, out value))
            {
                return (T)value;
            }

            return default(T);
        }

        /// <summary>
        /// Sets the specified expression.
        /// </summary>
        /// <typeparam name="T">Property type</typeparam>
        /// <param name="expression">The expression.</param>
        /// <param name="value">The value.</param>
        public void Set<T>(Expression<Func<T>> expression, T value)
        {
            var propertyName = PropertyNameProvider.GetPropertyName(expression);

            if (_values.ContainsKey(propertyName))
            {
                _values[propertyName] = value;
            }
            else
            {
                _values.Add(propertyName, value);
            }

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
